<template>
  <div class="search-suggestion">
    <van-cell v-for="(item,ind) in suggestion" :key='ind' icon="search" @click="$emit('searchSuggest',item)">
      <!-- 处理高亮 -->
      <div slot="title" v-html="highLight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
// 导入接口
import { getSearchSuggestion } from '@/api/search.js'
// 导入节流
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      suggestion: [],
      // 控制组件销毁
      isShow: true
    }
  },
  methods: {
    // 高亮字体处理
    highLight (item) {
      const reg = new RegExp(this.searchText, 'gi')
      return item.replace(reg, `<span style="color:red;">${this.searchText}</span>`)
    },
    // 加载联想搜索数据
    async loadSuggestion () {
      try {
        const { data: res } = await getSearchSuggestion(this.searchText)
        // console.log(res)
        this.suggestion = res.data.options
      } catch (err) {
        this.$toast('搜索联想失败')
      }
    }
  },
  computed: {},
  watch: {
    searchText: {
      // handler (val) {
      //   clearTimeout(time)
      //   const time = setTimeout(() => {

      //   }, 500);
      // }
      // 监视函数
      // debounce 参数一 要处理的函数  参数二延时时间
      // debounce  返回值为一个函数
      handler: debounce(function (val) {
        // console.log(this)
        if (!this.isShow) return
        // console.log(val)
        this.loadSuggestion()
      }, 500),
      // 首次加载
      immediate: true
    }
  },
  filters: {},
  components: {},
  created () { },
  mounted () { },
  beforeDestroy () {
    this.isShow = false
  }
}
</script>

<style lang='less' scoped>
</style>
